package com.zcsy.manage.web.property;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.commons.util.DateUtils;
import com.zcsy.commons.util.PoiUtils;
import com.zcsy.manage.model.base.CellBuilding;
import com.zcsy.manage.model.base.CellHouse;
import com.zcsy.manage.model.base.CellInfo;
import com.zcsy.manage.model.base.CellRegion;
import com.zcsy.manage.model.base.CellUnit;
import com.zcsy.manage.model.property.FeeBill;
import com.zcsy.manage.model.property.FeeBillDetail;
import com.zcsy.manage.model.system.Dict;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.service.base.ICellBuildingService;
import com.zcsy.manage.service.base.ICellHouseService;
import com.zcsy.manage.service.base.ICellInfoService;
import com.zcsy.manage.service.base.ICellRegionService;
import com.zcsy.manage.service.base.ICellUnitService;
import com.zcsy.manage.service.property.IFeeBillDetailService;
import com.zcsy.manage.service.property.IFeeBillService;
import com.zcsy.manage.service.system.IDictService;
import com.zcsy.manage.web.common.LogUtils;
import com.zcsy.manage.web.tools.JExcelReport;

/**
 * @Title: FeeBillController.java
 * @Package： com.zcsy.manage.web.property
 * @Description: 物业缴费记录控制层管理类
 * @author xujl
 * @Copyright: 2015 武汉中财数元信息技术有限公司 All rights reserved.
 * @date 2016年4月14日
 * @version 1.0
 * @see JDK1.7.0_75
 * @since
 */
@Controller
@RequestMapping(value = "/feeBill")
public class FeeBillController {

    @Autowired
    private IFeeBillService billService;

    @Autowired
    private IFeeBillDetailService detailService;

    @Autowired
    private ICellBuildingService cellBuildingService;

    @Autowired
    private ICellInfoService cellInfoService;

    @Autowired
    private ICellRegionService cellRegionService;

    @Autowired
    private ICellUnitService cellUnitService;

    @Autowired
    private ICellHouseService cellHouseService;

    @Autowired
    private IDictService dictService;

    private static final int ADD_MONTH = 1;// 月数增加量

    private static final int HOUSE_TYPE = -1; // 全部房屋类型

    private static final int HOUSE_STATE = -1; // 全部房屋状态

    private static final int DETAIL_LIST = 1; // 跳转到房间的账单记录

    private static final int UP_FILE = 3; // 弹出批量导入框

    /**
     * @Description 根据查询条件分页获取缴费数据列表
     * @param model
     * @param pNo
     *            当前页
     * @param cellId
     *            小区id
     * @param regionId
     *            区域id
     * @param buildingId
     *            楼栋id
     * @param unitId
     *            单元id
     * @param houseId
     *            房屋id
     * @param req
     *            用户的请求
     * @return 返回的结果
     * @author xujl
     * @date 2016年4月19日
     * @see
     */
    @RequestMapping(value = "infoList", method = RequestMethod.GET)
    public String infoList(Model model, Integer pNo, Integer pSize, String regionId,
    		String buildingId, String unitId, String houseId, HttpServletRequest req) {
        if (pNo == null) {
            pNo = Constants.PAGE_NO;
        }

		Integer pageSize;
		if (pSize == null) {
			pageSize = Constants.PAGE_SIZE;
		} else {
			switch (pSize) {
				case 0: pageSize = Constants.PAGE_SIZE;
				break;
				case 1: pageSize = Constants.PAGE_SIZE_TWENTY;
				break;
				case 2: pageSize = Constants.PAGE_SIZE_FIFTY;
				break;
				default:pageSize = Constants.PAGE_SIZE;
				break;
			}
		}
		
        // 此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
        PageHelper.startPage(pNo, pageSize);

        FeeBill record = new FeeBill();
        
        //获取当前小区id
        User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        String cellId = user.getCurrentCell().getId();
        record.setCellId(cellId);
        
        // 标题不为空时，设置标题
        if (StringUtils.isNotEmpty(regionId)) {
            record.setRegionId(regionId);
        }
        if (StringUtils.isNotEmpty(buildingId)) {
            record.setBuildingId(buildingId);
        }
        if (StringUtils.isNotEmpty(unitId)) {
            record.setUnitId(unitId);
        }
        if (StringUtils.isNotEmpty(houseId)) {
            record.setHouseId(houseId);
        }

        List<FeeBill> billList = billService.selectPropertyFeeBill(record);
        PageInfo<FeeBill> info = new PageInfo<FeeBill>(billList);

//        List<CellInfo> cellInfos = cellInfoService.getAllCellInfo();
     
        List<Dict> dictList = dictService.getDictFromCache("houseTypes");
        model.addAttribute("houseTypes", dictList);

        model.addAttribute("billInfo", info);
        model.addAttribute("currentPage", pNo);
		model.addAttribute("pSize", pSize);
        model.addAttribute("cellId", cellId);
        model.addAttribute("regionId", regionId);
        model.addAttribute("buildingId", buildingId);
        model.addAttribute("unitId", unitId);
        model.addAttribute("houseId", houseId);

        //从缓存中获取缴费状态
		List<Dict> billStates = dictService.getDictFromCache("billState");
		model.addAttribute("billStates", billStates);

		List<Dict> pageSizes = dictService.getDictFromCache("pageSize");
		model.addAttribute("pageSizes", pageSizes);

        return "property/feebill/billList";
    }

    /**
     * @Description 根据房间号得到账单列表<br>
     * @param houseId
     *            房间号
     * @return 跳转画面URL
     * @author xujl
     * @date 2016年4月14日
     * @see
     */
    @RequestMapping(value = "gotoDetail", method = RequestMethod.GET)
    public String gotoDetail(Model model, String houseId) {

        String url = "";
        try {

            List<Dict> payList = dictService.getDictFromCache("payWay");
            model.addAttribute("payWays", payList);

            CellHouse house = cellHouseService.selectByPrimaryKey(houseId);
            List<FeeBillDetail> detailList = detailService.selectByHouseIdAndState(houseId);

            model.addAttribute("house", house);
            model.addAttribute("detailList", detailList);
            url = "property/feebill/billDetail";

        } catch (Exception e) {
        }
        return url;
    }

    /**
     * @Description 根据房间号得到账单列表<br>
     * @param houseId
     *            房间号
     * @return 跳转画面URL
     * @author xujl
     * @date 2016年4月14日
     * @see
     */
    @RequestMapping(value = "initList", method = RequestMethod.GET)
    public String initList(Model model, Integer type, String houseId, HttpServletRequest req) {
        // 获取当前小区信息
        User user = (User) req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        String cellId = user.getCurrentCell().getId();
        String url = "";
        try {
            model.addAttribute("type", type);
            if (type == DETAIL_LIST || type == UP_FILE) {
                CellInfo cellInfo = cellInfoService.selectByPrimaryKey(cellId);
                model.addAttribute("cellInfo", cellInfo);
                url = "property/feebill/initList";
            } else {
                FeeBillDetail detail = detailService.selectLastBill(houseId);
                //获取房屋的物业费单价给账单的单价赋值
                CellHouse cellHouse = cellHouseService.selectByPrimaryKey(houseId);
                BigDecimal perPrice = cellHouse.getPerPrice();
                detail.setUnitPrice(perPrice);
                
                Date startDate = getStartDate(detail.getEndDate());
                model.addAttribute("bill", detail);
                model.addAttribute("startDate", startDate);
                model.addAttribute("houseId", houseId);
                url = "property/feebill/billEdit";
            }

        } catch (Exception e) {
        }
        return url;
    }

    /**
     * @description 物业费账单"后台缴费功能
     * @param houseId 房屋id
     * @param month 缴费月份
     * @param money 缴费钱数
     * @param beginDate 缴费开始日期
     * @param endDate 缴费结束日期
     * @param billType 发票类型
     * @param billTitle 发票抬头
     * @param billId 账单id
     * @param area 房屋面积
     * @param rate 倍率
     * @param unitPrice 单价
     * @author chenxin
     * @date 2016年9月9日上午11:27:26
     */
    @RequestMapping(value = "saveBill", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson saveBill(Model model, String houseId, Integer month, BigDecimal money, String beginDate,
            String endDate, Integer billType, String billTitle, HttpServletRequest request, String billId,
            BigDecimal area, BigDecimal rate, BigDecimal unitPrice) {

        RequestJson result = new RequestJson();
        final HttpSession session = request.getSession();
        User user = (User) session.getAttribute(RequestConstants.USER_SESSION_ID);

        if (billType == null) {
            billType = Constants.SELECT_NONE;
        }
        if (StringUtils.isNotEmpty(billTitle)) {
            billTitle = "";
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date beginD = DateUtils.str2Date(beginDate, sdf);
        Date endD   = DateUtils.str2Date(endDate, sdf);
        
        try {
            detailService.backGroundPay(beginD,endD,houseId, month, user, billId, billType, area, rate, unitPrice, billTitle,money);
            result.setMsg("成功缴纳物业费！！");
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMsg("操作异常！！");
        }
        return result;
    }
    
    /**
     * @Description 初始化账单信息
     * @param cellId 小区id
     * @param regionId 区域id
     * @param buildingId 楼栋id
     * @param unitId 单元id
     * @param houseId 房屋id
     * @param beginDate 开始日期
     * @param request 用户的请求
     * @param response 返回的结果
     * @author xujl
     * @date 2016年4月20日
     */
    @RequestMapping(value = "initBillList", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson initBillList(Model model, String cellId, String regionId, String buildingId, String unitId,
            String houseId, String beginDate, HttpServletResponse response, HttpServletRequest request) {

        RequestJson result = new RequestJson();
        User user = (User) request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        List<CellHouse> houseList = new ArrayList<CellHouse>();

        try {
            houseList = getHouseList(cellId, regionId, buildingId, unitId, houseId);

            if (houseList.isEmpty()) {
                result.setMsg("查询房屋失败，无法初始化");
                result.setSuccess(false);
                return result;
            }
            
            FeeBill bill = null;
            FeeBillDetail detail = null;

            Date bDate = DateUtils.str2Timestamp(beginDate);

            int count = 0;// 计算成功初始化多少个

            // 当前时间 >= 合同上的约定时间，生成一张账单，两张账单详情！正常和欠费账单。
            if (DateUtils.getMillis() >= bDate.getTime()) {
                for (CellHouse house : houseList) {
                    bill = new FeeBill();
                    detail = new FeeBillDetail();

                    bill.setHouseId(house.getId());
                    bill.setCellId(house.getCellId());
                    
                    List<FeeBill> feeBills = billService.selectByKeyword(bill);
                    //房屋没有账单  && 房屋有物业费单价 才能初始化
                    if (feeBills.size() == 0 && null != house.getPerPrice()) {
                        // 约定日期->约定日期的正常账单：金额是零
                        bill.setId(UniqueNumberUtils.get18UniqueNumber());
                        bill.setCellId(house.getCellId());
                        bill.setHouseId(house.getId());
                        bill.setSendTime(DateUtils.getDate());
                        
                        billService.insert(bill);

                        // 第一个正常账单的详情
                        detail.setStartDate(bDate);
                        detail.setEndDate(bDate);
                        detail.setCreateTime(DateUtils.getDate());
                        detail.setPayTime(DateUtils.getDate());
                        detail.setUpdateTime(DateUtils.getDate());
                        detail.setState(Constants.NORMAL_STATE);
                        initBill(house, bill, detail);

                        //第二个欠费账单详情：从约定日期算起到 N月后的欠费账单的详情
                        detail = new FeeBillDetail();
                        detail.setStartDate(bDate);
                        Integer NMonth = detailService.getDiffMonth(bDate, DateUtils.getDate());//两个日期之间相差N个月
                        detail.setEndDate(getAfterNMonth(bDate,NMonth));
                        detail.setCreateTime(DateUtils.getDate());
                        detail.setUpdateTime(DateUtils.getDate());
                        detail.setState(Constants.AFTER_STATE);
                        detail.setMonth(NMonth);
                        initBill(house, bill, detail);

                        count++;
                    }
                }
            } else {// 合同上的约定时间大于当前时间时：只生成一张从约定时间开始到约定时间结束的账单，金额是零。
                for (CellHouse house : houseList) {
                    bill = new FeeBill();
                    detail = new FeeBillDetail();

                    bill.setHouseId(house.getId());
                    bill.setCellId(house.getCellId());

                    // 查询每个房屋是否已经存在了账单，已存在的不能初始化！（因为数据库中数据错误，有的房间已经存在多个账单，故返回的账单用List）
                    List<FeeBill> feeBills = billService.selectByKeyword(bill);

                    if (feeBills.size() == 0) {
                        bill.setId(UniqueNumberUtils.get18UniqueNumber());
                        bill.setCellId(house.getCellId());
                        bill.setHouseId(house.getId());
                        bill.setSendTime(bDate);
                        billService.insert(bill);

                        detail.setStartDate(bDate);
                        detail.setEndDate(getAfterMonth(bDate));
                        detail.setCreateTime(DateUtils.getDate());
                        detail.setPayTime(DateUtils.getDate());
                        detail.setUpdateTime(DateUtils.getDate());
                        detail.setState(Constants.NORMAL_STATE);

                        initBill(house, bill, detail);
                        count++;
                    }
                }
            }
            result.setMsg("成功初始化了账单" + count + "个！");
            result.setSuccess(true);
            LogUtils.insertLog("用户初始化账单信息", user.getId(), request);
        } catch (Exception e) {
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * @Description 得到初始化的房间列表
     * @param cellId
     *            小区id
     * @param regionId
     *            区域id
     * @param buildingId
     *            楼栋id
     * @param unitId
     *            单元id
     * @param houseId
     *            房屋id
     * @return
     * @author xujl
     * @date 2016年4月21日
     * @see
     */
    private List<CellHouse> getHouseList(String cellId, String regionId, String buildingId, String unitId, String houseId) {
        List<CellHouse> houseList = null;
        try {
            CellHouse record = new CellHouse();
            record.setCellId(cellId);
            record.setHouseType(HOUSE_TYPE);
            record.setHouseState(HOUSE_STATE);

            if (StringUtils.isEmpty(regionId)) {
                houseList = cellHouseService.selectByKeyword(record);
            } else {
                record.setRegionId(regionId);
                if (StringUtils.isEmpty(buildingId)) {
                    houseList = cellHouseService.selectByKeyword(record);

                } else {
                    record.setBuildingId(buildingId);
                    if (StringUtils.isEmpty(unitId)) {
                        houseList = cellHouseService.selectByKeyword(record);
                    } else {
                        record.setUnitId(unitId);
                        if (StringUtils.isEmpty(houseId)) {
                            houseList = cellHouseService.selectByKeyword(record);
                        } else {
                            record.setId(houseId);
                            houseList = cellHouseService.selectByKeyword(record);
                        }

                    }

                }
            }
        } catch (Exception e) {
        }

        return houseList;
    }

    /**
     * @Description 初始化插入账单与缴费详情
     * @param house 房间对象
     * @param bill  账单对象
     * @param detail 缴费详情对象
     * @return 插入的结果
     * @author xujl
     * @date 2016年4月21日
     * @see
     */
    private int initBill(CellHouse house, FeeBill bill, FeeBillDetail detail) {
        int flag = Constants.SQL_RESULT_ERROR;
        
        try {
            detail.setId(UniqueNumberUtils.get18UniqueNumber());
            detail.setBillId(bill.getId());
            detail.setArea(house.getArea());
            detail.setRate(Constants.INIT_RATE);
            detail.setUnitPrice(house.getPerPrice());
            detail.setPayWay(Constants.PAY_WAY_HOUTAI);
            detail.setGenerateWay(Constants.GENERATE_WAY_INIT);
            int type = Constants.COMPANY_TYPE_PROPERTY;
            detail.setOperatorType(type);
            
            if(detail.getState() == Constants.AFTER_STATE) {
//                detail.setMonth(Constants.ONE_MONTH);
                detail.setMoney(detail.getRate().multiply(detail.getArea()).multiply(detail.getUnitPrice()).multiply(new BigDecimal(detail.getMonth())).setScale(Constants.MENU_LEVEL_SECOND));
            } else {
                detail.setMonth(Constants.INIT_MONTH);
                detail.setMoney(Constants.INIT_MONEY);
            }
            detailService.insert(detail);
            flag = Constants.SQL_RESULT_SUCCESS;
            
        } catch (Exception e) {
            flag = Constants.SQL_RESULT_FAILD;
        }

        return flag;
    }

    /**
     * @Description 计算下个月
     * @param beginDate
     *            开始日期
     * @return 下个月的日期
     * @author xujl
     * @date 2016年4月21日
     * @see
     */
    public static Date getAfterMonth(Date beginDate) {
        Calendar c = Calendar.getInstance();// 获得一个日历的实例
        // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        c.setTime(beginDate);// 设置日历时间
        c.add(Calendar.DAY_OF_MONTH, -1); // 设置为前一天
        c.add(Calendar.MONTH, ADD_MONTH);// 在日历的月份上增加1个月

        Date strDate = c.getTime();// 的到你想要得6个月后的日期
        return strDate;

    }
    
    public static Date getAfterNMonth(Date beginDate,Integer NMonth) {
        Calendar c = Calendar.getInstance();// 获得一个日历的实例
        // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        c.setTime(beginDate);// 设置日历时间
//        c.add(Calendar.DAY_OF_MONTH, -1); // 设置为前一天
        c.add(Calendar.MONTH, NMonth);// 在日历的月份上增加N个月
        Date strDate = c.getTime();// 的到你想要得N个月后的日期
        return strDate;

    }

    /**
     * @Description 计算下个月
     * @param beginDate
     *            开始日期
     * @return 下个月的日期
     * @author xujl
     * @date 2016年4月21日
     * @see
     */
    public static Date getStartDate(Date beginDate) {
        Calendar c = Calendar.getInstance();// 获得一个日历的实例
        // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        c.setTime(beginDate);// 设置日历时间
        c.add(Calendar.DAY_OF_MONTH, 1); // 设置为前一天

        Date strDate = c.getTime();// 的到你想要得6个月后的日期
        return strDate;

    }

    /**
     * @Description 根据小区或者区域级联查询下一级的数据
     * @param model
     * @param id
     *            本级id
     * @param num
     *            请求的类型 ：1：小区 2：区域 3：楼栋 4：单元
     * @param request
     *            用户的请求
     * @param response
     *            返回的结果
     * @return
     * @author xujl
     * @date 2016年4月19日
     * @see
     */
    @RequestMapping(value = "changeAddr", method = RequestMethod.GET)
    @ResponseBody
    public RequestJson changeAddr(Model model, String id, Integer num, HttpServletRequest request,
                                  HttpServletResponse response) {
        RequestJson result = new RequestJson();

        try {
            if (num == Constants.CELL_TYPE) {
                CellRegion record = new CellRegion();
                record.setCellId(id);

                List<CellRegion> list = cellRegionService.selectByKeyword(record);
                result.setObj(list);
            }
            if (num == Constants.REGION_TYPE) {
                CellBuilding record = new CellBuilding();
                record.setRegionId(id);

                List<CellBuilding> list = cellBuildingService.selectByKeyword(record);
                result.setObj(list);
            }
            if (num == Constants.BUILDING_TYPE) {
                CellUnit record = new CellUnit();
                record.setBuildingId(id);

                List<CellUnit> list = cellUnitService.selectByKeyword(record);
                result.setObj(list);
            }
            if (num == Constants.UNIT_TYPE) {
                CellHouse record = new CellHouse();
                record.setUnitId(id);
                record.setHouseType(HOUSE_TYPE);
                record.setHouseState(HOUSE_STATE);

                List<CellHouse> list = cellHouseService.selectByKeyword(record);
                result.setObj(list);
            }
            
            result.setMsg("更新成功");
            result.setSuccess(true);
            
        } catch (Exception e) {
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * @Description 根据多个id报修信息<br>
     * @param iDs
     *            多个id
     * @param req
     *            用户请求
     * @return 请求结果
     * @author xujl
     * @date 2016年4月14日
     * @see
     */
    @RequestMapping(value = "deleteInfo", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson deleteInfo(String iDs, HttpServletRequest req) {

        RequestJson result = new RequestJson();
        User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        try {
            String ids[] = iDs.split("\\,");
            for (int i = 0; i < ids.length; i++ ) {
                billService.deleteByPrimaryKey(ids[i]);
            }
            result.setSuccess(true);
            LogUtils.insertLog("用户删除报修信息", user.getId(), req);
        } catch (NumberFormatException e) {
            result.setSuccess(false);
            result.setMsg("操作失败");
        }
        return result;
    }

    /**
     * @Description 导出物业费清单<br>
     * @param response
     * @author xujl
     * @date 2016年5月3日
     * @see
     */
    @RequestMapping("/exportFeeBillExcel")
    @ResponseBody
    public void exportFeeBillExcel(String regionId, String buildingId,
            String unitId, String houseId, HttpServletResponse response, HttpServletRequest request) {
        List<FeeBill> list;
        FeeBill record = new FeeBill();
        User user = (User)request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
		String cellId = user.getCurrentCell().getId();

        // 标题不为空时，设置标题
        if (StringUtils.isNotEmpty(cellId)) {
            record.setCellId(cellId);
        }
        if (StringUtils.isNotEmpty(regionId)) {
            record.setRegionId(regionId);
        }
        if (StringUtils.isNotEmpty(buildingId)) {
            record.setBuildingId(buildingId);
        }
        if (StringUtils.isNotEmpty(unitId)) {
            record.setUnitId(unitId);
        }
        if (StringUtils.isNotEmpty(houseId)) {
            record.setHouseId(houseId);
        }

        try {
            // 得到导出的数据列表
            list = billService.selectByKeyword(record);
			
            // 将订单对象转化为到处所需要的数据格式
            Integer type;
            if (list.size() > 0) {
                ArrayList<ArrayList<String>> dataList = new ArrayList<ArrayList<String>>();
                int index = 1;
                for (FeeBill bill : list) {
                    ArrayList<String> temp = new ArrayList<String>();
                    // 序号
                    temp.add(String.valueOf(index++ ));
                    temp.add(bill.getId());
                    temp.add(bill.getCellName());
                    temp.add(bill.getRegionName());
                    temp.add(bill.getBuildingName());
                    temp.add(bill.getUnitName());
                    temp.add(bill.getHouseName());
                    type = bill.getState();
                    String label = dictService.selectByFilter(type,"billStates").getLabel();
                    temp.add(label);
                    temp.add(DateUtils.formatDate(bill.getEndDate()));
                    temp.add(bill.getMoney().toString());
                    dataList.add(temp);
                }
                // 导出标题列
                String[] rows = new String[] {"序号", "账单号", "小区名", "区域名", "楼栋名", "单元名", "房间号",
                    "缴费状态", "缴费到期时间", "缴费金额"};
                // 导出excel文件每列宽度
                int[] style = new int[] {5, 20, 20, 20, 20, 10, 20, 15, 20, 15};
                // Excel文件sheet名称
                String sheetName = "物业费清单" + DateUtils.getCurrentDate();
                String fileName = "物业费清单";
                doExecl(response, fileName, sheetName, dataList, rows, style);
                LogUtils.insertLog("导出物业费清单", user.getId(), request);
            }
        } catch (Exception e) {
            return;
        }
    }

    /**
     * @Description 通过传入的对象信息集合产生的excel表格<br>
     * @param response
     *            用户响应
     * @param sheetName
     *            excel表名称
     * @param dataList
     *            传入的数据列表
     * @param rows
     *            excel表的列控制，名称
     * @param style
     *            规定列宽等样式
     * @throws Exception
     * @author xujl
     * @date 2016年5月3日
     * @see
     */
    private void doExecl(HttpServletResponse response, String tempName, String sheetName,
                         ArrayList<ArrayList<String>> dataList, String[] rows, int[] style)
        throws Exception {
        // 输出的excel名称为中文，否则发生错误
        String tempFileName = tempName + ".xls";
        String fileName = new String(tempFileName.getBytes("GB2312"), "ISO_8859_1");

        ServletOutputStream fout = response.getOutputStream();
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "filename=" + fileName + "");
        JExcelReport jexcelOutStream = new JExcelReport();
        try {
            jexcelOutStream.excelreport(sheetName, dataList, rows, fout, style);
            fout.flush();
            fout.close();
        } catch (Exception e) {
        }

    }

    /**
     * @Description 站点信息导入(直接导入站点的入口)<br>
     * @param request
     * @param response
     * @return
     * @author tanghan barbadosliy@163.com
     * @date 2015年9月3日
     * @see
     */
    @RequestMapping("/importFeeBill")
    @ResponseBody
    public RequestJson importFeeBill(@RequestParam("cellId") String cellId,HttpServletRequest request,
                                     HttpServletResponse response) {
        response.setContentType("text/html;charset=utf-8");
        RequestJson json = new RequestJson();
        final HttpSession session = request.getSession();
        User user = (User)session.getAttribute(RequestConstants.USER_SESSION_ID);
        String errorMsg = "";
        
        MultipartHttpServletRequest multipartRequest  =  (MultipartHttpServletRequest) request;  
        MultipartFile imgFile  =  multipartRequest.getFile("fileIds");
        
        CommonsMultipartFile cf= (CommonsMultipartFile)imgFile; 
        DiskFileItem fi = (DiskFileItem)cf.getFileItem(); 
        File f = fi.getStoreLocation();
        
        String fileNames = imgFile.getOriginalFilename();
        long fileSize = imgFile.getSize();
        String extend = fileNames.substring(fileNames.lastIndexOf(".") + 1);
        

        if (!"xls".equalsIgnoreCase(extend) && !"xlsx".equalsIgnoreCase(extend)) {// 文件格式
            json.setSuccess(false);
            json.setMsg("请选择excel格式文件上传！");
        } else if (fileSize > 1024 * 1024 * 10) {// 文件大小(2Mb)
            json.setSuccess(false);
            json.setMsg("导入文件大小不得大于10Mb！");
        } else {
            InputStream inputStream = null;
            try {
                InputStream is = new FileInputStream(f);
                // 解析xls
                List<List> list = PoiUtils.parseExcelToString(is, 13, 2, 0);
                if (!list.isEmpty()) {
                    // 检查数据格式是否有错
                    errorMsg = billService.findBug(cellId, list);

                    if (errorMsg.equals("")) {
                        // 效验...
                         int message = billService.importFeeBill(list, cellId, user);
                        json.setSuccess(true);
                        json.setMsg("文件导入成功！");
                    } else {
                        json.setSuccess(false);
                        json.setMsg(errorMsg.toString());
                    }
                } else {
                    json.setSuccess(false);
                    json.setMsg("文件数据错误！");
                }
                
            } catch (Exception e) {
                e.printStackTrace();
                json.setSuccess(false);
                json.setMsg("文件格式错误！");
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {}
                }
            }
        }

        return json;
    }

}
